package com.bjpowernode.dataservice.impl;

import com.bjpowernode.common.P2PConstants;
import com.bjpowernode.common.P2PKey;
import com.bjpowernode.mapper.LoanInfoMapper;
import com.bjpowernode.model.LoanInfo;
import com.bjpowernode.model.ext.BidLoanInfo;
import com.bjpowernode.service.LoanInfoService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

@DubboService(interfaceClass = LoanInfoService.class)
public class LoanInfoServiceImpl implements LoanInfoService{

    @Resource
    private LoanInfoMapper loanInfoMapper;

    @Resource
    private RedisTemplate redisTemplate;


    //历史年化收益率
    @Override
    public BigDecimal queryHistoryAvgTate() {

        //放入redis缓存
        ValueOperations valueOperations =redisTemplate.opsForValue();
        BigDecimal avgRate = (BigDecimal) valueOperations.get(P2PKey.P2P_HISTORY_AVG_RATE);
        if (avgRate==null){
            avgRate=(BigDecimal) valueOperations.get(P2PKey.P2P_HISTORY_AVG_RATE);
            if (avgRate==null){
                avgRate = loanInfoMapper.selectHistoryAvgRate();
                valueOperations.set(P2PKey.P2P_HISTORY_AVG_RATE,avgRate,20, TimeUnit.MINUTES);
            }
        }
       return avgRate;
    }

    @Override
    public List<LoanInfo> queryLoanPageByProductType(Integer productType,
                                                     Integer pageNo,
                                                     Integer pageSize) {
        //计算limit语句的起始位置 limit offset,rows
        //offset:表示从第几行数据开始查；rows:表示查几条数据=pageSize
        int offset = (pageNo-1)*pageSize;
        List<LoanInfo> XSBLoanInfoList =loanInfoMapper.selectPageByProductType(productType,
                offset,pageSize);
        //loanInfoList不会是null,要么是0个成员，要么是>0的。

        return XSBLoanInfoList;
    }

    /**
     *
     * @param productType
     * @return
     */
    @Override
    public int queryRecordNumByProductType(Integer productType) {

        return loanInfoMapper.selectCountRecordNums(productType);
    }

    /**
     * 根据主键查询单个LoanInfo
     * @param loanId
     * @return
     */
    @Override
    public LoanInfo queryLoanInfoByIb(Integer loanId) {

        LoanInfo loanInfo=loanInfoMapper.selectLoanInfoByPrimaryKey(loanId);
        return loanInfo;
    }


}
